﻿using System;
using System.Text;
using System.Linq;
using Dapper;
using Dapper.Contrib.Extensions;

namespace EC.Application.Impl
{
    using EC.Application.Interface;
    using EC.Entity;
    using EC.Entity.Query;
    using EC.Entity.Request.UserGroup;
    using EC.Entity.Response.UserGroup;
    using EC.Entity.Tables;

    /// <summary>
    /// 
    /// </summary>
    public class UserGroupServiceImpl: UserGroupService
    {
        #region 注入
        /// <summary>
        /// 数据接口
        /// </summary>
        private readonly IDBSession _dbSession;


        /// <summary>
        /// 数据库上下文
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public UserGroupServiceImpl(IDBSession dbSession)
        {
            _dbSession = dbSession;
        }
        #endregion

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public UserGroupResponse Get(int id)
        {
            var userGroupResponse = _dbSession.DbConnection.QueryFirst<UserGroupResponse>("select * from usergroup where Id=@Id", new { Id = id });
            if (userGroupResponse != null)
            {
                return userGroupResponse;
            }
            return null;
        }

        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public string GetUserGroup(int userId)
        {
            var userGroups = _dbSession.DbConnection.Query<UserGroupResponse>("select ug.* from user u INNER JOIN usergroup ug on u.UserGroupId =ug.Id WHERE u.Id=@Id", new { Id = userId });

            var userGroup = userGroups.FirstOrDefault();
            if (userGroup != null)
            {
                return userGroup.MerchantIds;
            }

            return "";
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult Save(SaveUserGroupRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            if (request.Id > 0)
            {
                var userGroupNameExist = _dbSession.DbConnection.Query<UserGroupResponse>("SELECT * FROM usergroup WHERE Name=@Name AND Id!=@Id", new { Name = request.Name, request.Id });
                if (userGroupNameExist != null && userGroupNameExist.Any())
                {
                    throw new Exception("用户组名称已存在.");
                }

                var usergroup = _dbSession.DbConnection.QueryFirst<UserGroup>("select * from usergroup where Id=@Id", new { Id = request.Id });
                if (usergroup == null)
                {
                    throw new Exception("用户组记录不存在.");
                }

                usergroup.Name = request.Name;
                usergroup.MerchantIds = request.MerchantIds;
                usergroup.Status = request.Status.Value;
                //更新
                _dbSession.DbConnection.Update<UserGroup>(usergroup);

                response.Success = true;
            }
            else
            {
                var userGroupNameExist = _dbSession.DbConnection.Query<UserGroupResponse>("SELECT * FROM usergroup WHERE Name=@Name", new { Name = request.Name });
                if (userGroupNameExist != null && userGroupNameExist.Any())
                {
                    throw new Exception("用户组名称已存在.");
                }

                var usergroup = new UserGroup()
                {
                    Name = request.Name,
                    MerchantIds = request.MerchantIds,
                    Status = request.Status.Value,
                };

                //新增
                long resultId = _dbSession.DbConnection.Insert<UserGroup>(usergroup);

                if (resultId <= 0)
                {
                    throw new Exception("新增用户组失败.");
                }
                response.Success = true;
            }
            return response;
        }

        /// <summary>
        /// 状态
        /// </summary>
        /// <returns></returns>
        public JResult UpdateStatus(int id, sbyte status)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var bigclass = _dbSession.DbConnection.QueryFirst<UserGroup>("select * from usergroup where Id=@Id", new { Id = id });
                if (bigclass == null)
                {
                    throw new Exception("用户组记录不存在.");
                }

                var updateSql = "UPDATE usergroup SET Status=@Status WHERE Id=@Id";

                int result = _dbSession.DbConnection.Execute(updateSql, new { Status = status, Id = id });
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }

                response.Success = true;
                response.Message = "操作成功.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }
            return response;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<UserGroupQueryResponse> GetPager(UserGroupQuery query)
        {
            var currentPageIndex = 0;

            if (query.CurrentPageIndex.Value > 0)
            {
                currentPageIndex = (query.CurrentPageIndex.Value - 1) * query.PageSize.Value;
            }

            var files = "Id,MerchantIds,Name,Status";
            var tableName = "usergroup";
            var orderby = "ORDER BY Id DESC";
            var where = "where 1=1";

            #region 条件
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, currentPageIndex, query.PageSize.Value);

            using (var multi = _dbSession.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<UserGroupQueryResponse>();

                return new PagedList<UserGroupQueryResponse>()
                {
                    TData = list,
                    CurrentPageIndex = query.CurrentPageIndex.Value,
                    TotalCount = count
                };
            }
        }
    }
}
